import 'whatwg-fetch';
import 'es6-promise';

import NetTool from '../../../util/NetTool';

// Constants
export const TEST_QUERY = 'TEST_QUERY';
export const TEST_QUERYANDCHANGE = 'TEST_QUERYANDCHANGE';

// Actions
export const query = () => {
  return {
    type: TEST_QUERY
  };
};

export const queryandchange = () => {
  return (dispatch, getState) => {
    /*dispatch({
      type: TEST_QUERYANDCHANGE
    });*/
    return fetch('test.json')
      .then( response => response.json())
      .then( json => {
        dispatch({
          type: TEST_QUERYANDCHANGE,
          payload: json
        });
      })
      .catch( ex => console.log('parsing failed', ex));
  };
};

export const actions = {
  query,
  queryandchange
};

// Action Handlers
const ACTION_HANDLERS = {
  [TEST_QUERY]: (state, action) => {
    NetTool.get('test.json');
    console.log(state, action);
    return 'test';
  },
  [TEST_QUERYANDCHANGE]: (state, action) => {
    console.log(state, action);
    return action.payload.name;
  }
};

// Reducer
const initialState = '0';
export default function testReducer (state = initialState, action) {
  const handler = ACTION_HANDLERS[action.type];

  return handler ? handler(state, action) : state;
}
